/**
 * Created by shenhai on 15/9/2.
 */


var async = require('async');
var mysqlUtil = require('../../../common/utils/mysqlUtil');

exports.userListService = function(req ,callback) {

    var body = req.body;
    var size = Number(req.params.size);
    var index = (Number(req.params.page) - 1) * size;

    var sql1 = "select count(*) as count from sys_user where 1 = 1";
    var sql2 = "select * from sys_user where 1 = 1 order by dateCreate desc limit " + index +"," + size;


    if (body.loginName) {
        sql1 = sql1 + " and loginName like '%" + body.loginName + "%'";
        sql2 = "select * from sys_user where 1 = 1 and loginName like '%" + body.loginName +"%' order by dateCreate desc limit " + index +"," + size;
    }

    logger.debug(sql1);
    logger.debug(sql2);

    async.series([

        function (callbackInner) {
            mysqlUtil.query(sql1, function (err, result) {


                if (err || result.length == 0) {
                    callbackInner(err, null);
                }else {
                    var count = result[0].count;
                    var temp = {count: count, totalPage:Math.ceil(count/size)};

                    //logger.debug(temp);
                    callbackInner(err, temp);
                }

            });
        },

        function (callbackInner) {
            mysqlUtil.query(sql2, function (err, result) {

                if (err) {
                    callbackInner(err, null);
                }else {

                    //logger.debug("result");
                    //logger.debug(result);

                    if (result.length == 0) {
                        callbackInner(null, result);
                    }else {
                        var i = 0;
                        async.each(result, function(user, callbackInner2) {

                            user.isSupper = user.isSupper.readUInt8(0,[true]);
                            user.isValid = user.isValid.readUInt8(0,[true]);

                            var sql = "select roleID from sys_userInRole where sysUserID = " + user.sysUserID;
                            mysqlUtil.query(sql, function (err, role) {

                                //logger.debug("role");
                                //logger.debug(role);
                                user.role = role;
                                //logger.debug(result);

                                i++;
                                if (i == result.length) {
                                    callbackInner(null, result);
                                }

                            }, callbackInner2);
                            
                        });
                    }



                }
            });
        }

    ], callback);

};



exports.userAddService = function(req ,callback) {

    if (!(req.body.roleID && req.body.roleID.length)) {
        return callback("缺少角色id", null);
    }

    var body = req.body;
    logger.debug(body);

    body.isValid = 1;
    body.userLastModified = "1";
    var roleID = body.roleID;
    var userID = null;
    delete body.roleID;



    logger.debug(body);
    logger.debug("roleID");
    logger.debug(roleID);

    async.series([

        function (callbackInner) {

            var sql = "insert into sys_user set ?";

            mysqlUtil.query(sql, [body], function (err, result) {

                //logger.debug("result");
                //logger.debug(result);

                userID = result.insertId;
                callbackInner(err, result);
            });
        },

        function (callbackInner) {

            async.each(roleID, function (role, callbackInner2) {

                if (! userID) {

                    callbackInner2();

                }else {
                    var sql = "insert into sys_userInRole set ?";
                    mysqlUtil.query(sql, [{roleID:Number(role), sysUserID:userID}], function (err, result) {

                        callbackInner2();
                    });
                }

            }, callbackInner);

        },

    ], callback);

};



exports.userDeleteService = function(req ,callback) {

    var body = req.body;
    if (!(body.userID && body.userID.length)) {
        callback({domain:"没有sysUserID"}, null);
    }
    var userID = body.userID;
    logger.debug(userID);


    var temp = "(";
    for(var i = 0, leng = userID.length;i<leng;i++) {
        if (i == leng - 1) temp = temp + userID[i];
        else temp = temp + userID[i] +",";
    }
    temp += ")";


    async.series([

        function(callbackInner) {
            var sql = "delete from sys_user where sysUserID in " + temp;
            mysqlUtil.query(sql, callbackInner);
        },

        function(callbackInner) {
            var sql = "delete from sys_userInRole where sysUserID in " + temp;
            mysqlUtil.query(sql, callbackInner);
        },

    ], callback);

};


exports.userEditService = function(req ,callback) {

    logger.debug(req.body);

    var body = req.body;
    if (body.userID) body.userID = Number(body.userID);

    var userID = body.userID;
    var roleID = body.user.roleID;


    if (!userID) {
       return callback("没有userID", null);
    }

    if (!roleID) {
        var sql = 'update sys_user set ? where sysUserID = ?';
        mysqlUtil.query(sql, [body.user, body.userID], callback);

    }else {

        delete body.user.roleID;

        async.series([

            function (callbackInner) {

                var sql = 'update sys_user set ? where sysUserID = ?';
                mysqlUtil.query(sql, [body.user, body.userID], function (err, result) {
                    callbackInner(err, result);
                });
            },

            function (callbackInner) {

                var sql = "delete from sys_userInRole where  sysUserID = " + userID;
                mysqlUtil.query(sql, callbackInner);
            },

            function (callbackInner) {

                async.each(roleID, function (role, callbackInner2) {

                    var sql = "insert into sys_userInRole set ?";
                    mysqlUtil.query(sql, [{roleID:Number(role), sysUserID:userID}],callbackInner2);

                }, callbackInner);

            },

        ], callback);

    }


};

// mysqlUtil.query('update retailer set ? where id = ?', [input, id], callback)

exports.changePasswordService = function(req ,callback) {

    logger.debug(req.body);

    var body = req.body;
    var userID = Number(req.session.account.userID);

    async.series([

        function(callbackInner) {
            var sql = "select * from sys_user where sysUserID = "+ userID;
            mysqlUtil.query(sql, function (err, result) {

                if(result.length > 0){
                    if(result[0].passWord != body.oldpassWord){
                        callback({errmsg:'原密码输入错误!'});
                    }else{
                        callbackInner(err, result);
                    };
                }else{
                    return callback({errmsg:'用户不存在!'});
                };

            });
        },
        function(callbackInner) {
            delete body.oldpassWord;
            var sql = 'update sys_user set ? where sysUserID = ?';
            mysqlUtil.query(sql, [body, userID], function (err, result) {
                callbackInner(err, result);
            });
        }
    ], callback);
};